package middleware

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"kf/utils/R"
	"net/http"
	"runtime/debug"
)

type Err struct {
	Log *zap.Logger
}

func (err *Err) Recovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if r := recover(); r != nil {
				// 记录日志或处理错误
				err.Log.Error("Recovered in", zap.String("url", c.Request.URL.Path), zap.Any("stack", r), zap.Any("error", debug.Stack()))
				// 将panic转换为错误响应
				c.AbortWithStatusJSON(http.StatusInternalServerError, R.ReturnFailMsg(errorToString(r)))
			}
		}()
		c.Next() // 先调用c.Next()执行后面的中间件
	}
}

func errorToString(r any) string {
	switch v := r.(type) {
	case error:
		return v.Error()
	default:
		return r.(string)
	}
}
